package com.dji.GSDemo.GaodeMap.service;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.dji.GSDemo.GaodeMap.entity.FlyingPath;
import com.dji.GSDemo.GaodeMap.entity.Task;
import com.dji.GSDemo.GaodeMap.entity.Waypoint;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import dji.common.mission.waypoint.WaypointMission;
import dji.common.mission.waypoint.WaypointMissionFinishedAction;
import dji.common.mission.waypoint.WaypointMissionFlightPathMode;
import dji.common.mission.waypoint.WaypointMissionHeadingMode;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.FormBody;

public class MissionService {
    //"http://118.31.12.36:8080/http";
    static final String host = "http://118.31.12.36:8080/http";
    static final String publickeyUrl = "/getPublicKey";
    static final String taskListUrl = "/taskList";
    static final String pathListUrl = "/pathList";
    static final String wayPointListUrl = "/waypointList";
    static final String getPathByPathIdUrl = "/getPathByPathId";
    static final String updateTaskUrl = "/updateTask";
    static String publicKey;
    static  String account;
    static  String password;

    static {
        //初始化publicKey,account,password
        new Thread(()->publicKey = getPublickey()).start();
       // publicKey = getPublickey();
        System.out.println(publicKey);
        account=getAccount();
        password=getPassword();
    }

    /*
     基础方法
     */
    //从远程api获取data的封装，传入url+参数
    static String getMessageFromRemote(String url, RequestBody requestBody) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        final String[] result = {""};
        try {
            Response response = okHttpClient.newCall(request).execute();
            result[0] = response.body().string();
            System.out.println(url+" "+result[0]);
        } catch (IOException e) {
            System.out.println("出错啦++++++++");
            e.printStackTrace();
        }
        return result[0];
    }

    //获取公钥
    static String getPublickey() {
        RequestBody requestBody = new FormBody.Builder()
                .build();
        String json = getMessageFromRemote(host + publickeyUrl, requestBody);
        JsonElement element = new JsonParser().parse(json);
        JsonObject root = element.getAsJsonObject();
        return root.get("publicKey").getAsString();
    }

    //TODO：获取账户和密码 暂时不知道从哪里获取
     static String getAccount(){
        return "zhangsan";
    }
    static String getPassword(){
        return "123456";
    }

    /*
     操作task的方法
     */

    //json转tasklist
    public List<Task> getTaksListFromJson(String json) {
        System.out.println(json);
        JsonElement element = new JsonParser().parse(json);
        JsonObject root = element.getAsJsonObject();
        int code = root.get("code").getAsShort();
        //调用失败
        if (code < 0){
            //打印失败信息
            System.out.println(root.get("message"));
            return new ArrayList<>();
        }
        JsonArray data = root.getAsJsonArray("data");
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        List<Task> tasks = gson.fromJson(data.toString(), new TypeToken<List<Task>>() {
        }.getType());
        return tasks;
    }

    // 获取任务列表0：已取消1：未开始2：执行中3：已完成
    public  List<Task> getTaskList( int page, int limit, int finishStatus) {

        try {
            System.out.println("加密acc:"+RSAEncrypt.encrypt(account, publicKey));
            System.out.println("加密pas:"+RSAEncrypt.encrypt(password, publicKey));
            RequestBody requestBody = new FormBody.Builder()
                    .add("account", RSAEncrypt.encrypt(account, publicKey))
                    .add("password", RSAEncrypt.encrypt(password, publicKey))
                    .add("page", page + "")
                    .add("limit", limit + "")
                    .add("finishStatus",finishStatus+"")
                    .build();
            String json = getMessageFromRemote(host + taskListUrl, requestBody);
            return getTaksListFromJson(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<Task>();
    }
    //获取已完成任务
    public  List<Task> getFinishedTaskList( int page, int limit) {
        return getTaskList( page, limit, 3);
    }
    //获取未开始任务
    public  List<Task> getUnFinishedTaskList( int page, int limit) {
        return getTaskList( page, limit, 1);
    }
    //更新任务状态
    public  int updateTask(int taskId, String status, String finishStatus, String executestarttime, String executeendtime) {
        try {
            RequestBody requestBody = new FormBody.Builder()
                    .add("account", RSAEncrypt.encrypt(account, publicKey))
                    .add("password", RSAEncrypt.encrypt(password, publicKey))
                    .add("taskId", taskId + "")
                    .add("status", status)
                    .add("finishStatus", finishStatus)
                    .add("executestarttime", executestarttime)
                    .add("executeendtime", executeendtime)
                    .build();
            String json = getMessageFromRemote(host + updateTaskUrl, requestBody);
            JsonElement element = new JsonParser().parse(json);
            JsonObject root = element.getAsJsonObject();
            int code = root.get("code").getAsInt();
            return code;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }
    //根据pathid获取路径信息
    public FlyingPath getFlyingPath(int pathId) {
        try {
            RequestBody requestBody = new FormBody.Builder()
                    .add("account", RSAEncrypt.encrypt(account, publicKey))
                    .add("password", RSAEncrypt.encrypt(password, publicKey))
                    .add("id", pathId + "")
                    .build();
            String json = getMessageFromRemote(host + getPathByPathIdUrl, requestBody);
            return new Gson().fromJson(json, FlyingPath.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //把json字符串转成 waypoint list
    public  List<Waypoint> getWaypointListFromJson(String json) {
        JsonElement element = new JsonParser().parse(json);
        JsonObject root = element.getAsJsonObject();
        int code = root.get("code").getAsShort();
        //调用失败
        if (code < 0){
            //打印失败信息
            System.out.println(root.get("message"));
            return new ArrayList<>();
        }
        JsonArray data = root.getAsJsonArray("data");
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        List<Waypoint> waypoints = gson.fromJson(data, new TypeToken<List<Waypoint>>() {
        }.getType());
        return waypoints;
    }
    //根据pathId获取路径点集合
    public List<Waypoint> getWaypointList(int pathId) {
        try {
            RequestBody requestBody = new FormBody.Builder()
                    .add("account", RSAEncrypt.encrypt(account, publicKey))
                    .add("password", RSAEncrypt.encrypt(password, publicKey))
                    .add("pathId", pathId + "")
                    .build();
            String json = getMessageFromRemote(host + wayPointListUrl, requestBody);
            return getWaypointListFromJson(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
    public static void main(String[] args) {
        MissionService m=new MissionService();
        //获取公钥-->测试通过
       //获取任务列表-->测试通过
         m.getUnFinishedTaskList(1,10);
       //从任务中获取pathid进行path查询-->测试通过
        //m.getFlyingPath(17);
        //更新任务信息-->测试成功
       // m.updateTask(2,3+"",3+"","2020/03/09 00:00:00","2020/03/09 00:00:00");
        // 获取路径点集合-->测试成功
       // m.getWaypointList(17);
    }

    /*
    任务装配流程
    1.设置高度  速度  完成飞行任务后的动作
    2.在地图上面描绘点
    3.设置waypointList
     */

    //把FinishedAction字符转转成封装对象
    public  WaypointMissionFinishedAction getFinishedActionFromString(String mFinishedActionString){
        switch (mFinishedActionString){
            case "NO_ACTION":   return WaypointMissionFinishedAction.NO_ACTION;
            case "GO_HOME": return WaypointMissionFinishedAction.GO_HOME;
            case "AUTO_LAND":return WaypointMissionFinishedAction.AUTO_LAND;
            case "GO_FIRST_WAYPOINT" :  return WaypointMissionFinishedAction.GO_FIRST_WAYPOINT;
            default:return WaypointMissionFinishedAction.NO_ACTION;
        }

   }
   //把自己的waypoint转城Dji的waypoint
   public  List<dji.common.mission.waypoint.Waypoint> transfromToDjiWaypointList(List<Waypoint> waypointList){
        List<dji.common.mission.waypoint.Waypoint> result=new ArrayList<>();
        for (int i = 0; i < waypointList.size(); i++) {
            Waypoint waypoint=waypointList.get(i);
            dji.common.mission.waypoint.Waypoint mWaypoint = new dji.common.mission.waypoint.Waypoint(waypoint.getLatitude(),waypoint.getLongitude(), waypoint.getAltitude());
            result.add(mWaypoint);
        }
        return result;
    }
    //在地图上绘制一个点
    public  void markWaypoint(AMap aMap, Map<Integer, Marker> mMarkers, LatLng point,int number){
        //Create MarkerOptions object
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(point);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        Marker marker = aMap.addMarker(markerOptions);
        marker.setTitle("点序号:"+number);
        marker.setSnippet("纬度:"+point.latitude+";经度:"+point.longitude);
        mMarkers.put(mMarkers.size(), marker);
    }
    //在地图上绘制多个点
    public   boolean  markWaypointList(AMap aMap, Map<Integer, Marker> mMarkers,List<Waypoint> waypointList){
        for (int i = 0; i < waypointList.size(); i++) {
            markWaypoint(aMap,mMarkers,new LatLng(waypointList.get(i).getLatitude(),waypointList.get(i).getLongitude()),i+1);
        }
        return true;
    }
    //构造路径任务
    public  boolean buildWayPointMission(WaypointMission.Builder waypointMissionBuilder,float mSpeed,String mFinishedActionString,String mHeadingModeString,List<Waypoint> waypointList){
     //设置速度speed、HeadingMode、FinishedAction
        WaypointMissionHeadingMode mHeadingMode = WaypointMissionHeadingMode.AUTO;

       if (waypointMissionBuilder == null){
           waypointMissionBuilder = new WaypointMission.Builder().finishedAction(getFinishedActionFromString(mFinishedActionString))
                   .headingMode(mHeadingMode)
                   .autoFlightSpeed(mSpeed)
                   .maxFlightSpeed(mSpeed)
                   .flightPathMode(WaypointMissionFlightPathMode.NORMAL);

       }else
       {
           waypointMissionBuilder.finishedAction(getFinishedActionFromString(mFinishedActionString))
                   .headingMode(mHeadingMode)
                   .autoFlightSpeed(mSpeed)
                   .maxFlightSpeed(mSpeed)
                   .flightPathMode(WaypointMissionFlightPathMode.NORMAL);

       }
       //设置点集合
       waypointMissionBuilder.waypointList(transfromToDjiWaypointList(waypointList));
       return true;
    }


}
